<template>
	<view style="background-color: #fff;">
		<view id="filter-box" style="display: flex;font-size: 28rpx;">
			<picker @change="(e)=>{
				pickers.dateDictCurIndex = e.detail.value
			}" :value="pickers.dateDictCurIndex" :range="pickers.dateDict" range-key="label">
				<view 
					style="color:#4e77cf;display: flex;align-items: center;padding: 10rpx 20rpx;">
					<text>{{pickers.dateDict[pickers.dateDictCurIndex].label}}</text>
					<up-icon style="margin-left: 4rpx;" name="arrow-down-fill"
						color="#4e77cf" size="10"></up-icon>
				</view>
			</picker>
			<picker @change="(e)=>{
				pickers.userDictCurIndex = e.detail.value
			}" :value="pickers.userDictCurIndex" :range="pickers.userDict" range-key="label">
				<view :style="{color:pickers.userDictCurIndex!=0?'#4e77cf':''}"
					style="display: flex;align-items: center;padding: 10rpx 20rpx;">
					<text>{{pickers.userDict[pickers.userDictCurIndex].label}}</text>
					<up-icon style="margin-left: 4rpx;" name="arrow-down-fill"
						:color="pickers.userDictCurIndex!=0?'#4e77cf':''" size="10"></up-icon>
				</view>
			</picker>

			<view @click="toSelectCusPage" :style="{color:pickers.cusCurId!=null?'#4e77cf':''}"
				style="display: flex;align-items: center;margin-left: 20rpx;">
				<text>{{pickers.cusName}}</text>
				<up-icon style="margin-left: 4rpx;" name="arrow-down-fill"
					:color="pickers.cusCurId!=null?'#4e77cf':''" size="10"></up-icon>
			</view>
		</view>

		<view v-if="list.length === 0"
			:style="{height:mainBoxHeight-filterBoxHeight-paddingBottom+'px'}"
			style="display: flex;justify-content: center;align-items: center;">
			<up-empty mode="data" icon="data"></up-empty>
		</view>
		<scroll-view v-else :style="{height:mainBoxHeight-filterBoxHeight-paddingBottom+'px'}"
			@scrolltolower="scrolltolower" scroll-y>
			<view @click="itemClick(item)" v-for="(item, index) in list" :key="index"
				style="position: relative;padding: 20rpx;border-bottom: 1px solid #dcdfe6;">
				<view style="font-weight: bold;display: flex;justify-content: space-between;">
					<text>{{item.cusname}}</text>
					<text style="color:orangered">￥{{item.orderamount}}</text>
				</view>
				<view style="margin-top: 10rpx;color:#75747c;font-size: 28rpx;">
					{{item.saleid + " " + item.ownername}}
				</view>
				<view style="margin-top: 10rpx;color:#75747c;font-size: 28rpx;">
					单据时间：{{item.create_time}}
				</view>
				<view style="position: absolute;bottom:20rpx;right:20rpx">
					<up-tag :text="item.statu" plain size="mini" :type="getTagType(item)"></up-tag>
				</view>
			</view>
			<up-loadmore :status="status" />
			<view style="height: 30rpx;"></view>
		</scroll-view>


		<!-- 占位置 -->
		<view style="background-color: #ffffff;
					position: fixed;
					bottom: 0;
					left: 0;
					width: 100%;
					z-index: 998;
					box-sizing: content-box;
					border-top: 1px solid #dedede;
					padding-bottom: env(safe-area-inset-bottom);" id="bottom-box">
			<view style="margin-left: auto;text-align: right;padding: 20rpx;">
				<text>合计：</text>
				<text
					style="font-size: 48rpx;color:#C06E5D;font-weight: bold;">￥{{orderTotalPrice}}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import timeUtils from '@/utils/time.js'
	import { timeFormat } from '@/uni_modules/uview-plus';
	import Decimal from 'decimal.js'
	import { ref, reactive, watch, computed, onMounted } from 'vue'
	import { onReady, onLoad } from "@dcloudio/uni-app"
	import { useStore } from "vuex";
	const store = useStore();
	const app = getApp()

	const paddingBottom = ref(0) // 页面布局相关变量
	const mainBoxHeight = ref(0) // 页面布局相关变量
	const filterBoxHeight = ref(0) // 页面布局相关变量
	const date = new Date()
	const todayStr = timeFormat(date, 'yyyy-mm-dd')
	const pickers = reactive({
		dateDictCurIndex: 0,
		dateDict: [
			{ 'label': '今日', 'value': [todayStr, todayStr] },
			{ 'label': '近30天', 'value': [todayStr, timeUtils.getNDaysAgo(date, 30)] },
		],
		userDictCurIndex: 0,
		userDict: [{ 'label': '业务员', 'value': -1 }],
		cusCurId: null,
		cusName: '客户',
	})
	const status = ref('loadmore');
	const list = ref([]);
	const limitPage = ref({
		page: 1,
		limit: 10,
	})

	onMounted(async () => {
		uni.createSelectorQuery().select('#bottom-box').boundingClientRect(b_data => {
			paddingBottom.value = b_data.height
		}).exec()
		uni.createSelectorQuery().select('#filter-box').boundingClientRect(b_data => {
			filterBoxHeight.value = b_data.height
		}).exec()
	})

	onLoad(async (options) => {
		const userDictRes = await app.globalData.http.get("/sysUser/dict")
		pickers.userDict.push(...userDictRes.data)
		loadmore();
	})
	
	// 监听 dateDictCurIndex 变化
	watch(() => pickers.dateDictCurIndex, (newVal, oldVal) => {
		console.log('dateDictCurIndex 变化:', { newVal, oldVal })
	}, {
		immediate: false // 立即执行一次
	})
	
	// 监听 cusCurId 变化
	watch(() => pickers.cusCurId, (newVal, oldVal) => {
		console.log('cusCurId 变化:', { newVal, oldVal })
		// 在这里处理 cusCurId 变化的逻辑
		list.value = []
		limitPage.value = {
			page: 1,
			limit: 10,
		}
		loadmore();
	}, {
		immediate: false // 立即执行一次
	})

	// 监听 userDictCurIndex 变化
	watch(() => pickers.userDictCurIndex, (newVal, oldVal) => {
		console.log('userDictCurIndex 变化:', { newVal, oldVal })
		// 在这里处理 userDictCurIndex 变化的逻辑
		list.value = []
		limitPage.value = {
			page: 1,
			limit: 10,
		}
		loadmore();
	}, {
		immediate: false // 立即执行一次
	})
	// 合计
	const orderTotalPrice = computed(() => {
		return list.value.reduce((sum, item) => {
			const amount = new Decimal(item.orderamount || 0)
			return new Decimal(sum).plus(amount)
		}, new Decimal(0)).toNumber()
	})

	// 设置客户
	const setCus = (id, name) => {
		pickers.cusCurId = id
		pickers.cusName = name
	}

	// 设置组件高度
	const setMainBoxHeight = (height) => {
		mainBoxHeight.value = height
	}

	// 选择客户
	const toSelectCusPage = () => {
		uni.navigateTo({
			url: '/pages/selectCus'
		})
	}

	const itemClick = (item) => {
		uni.navigateTo({
			url: `/pageCarSale/carSaleOrderDetail?id=${item.saleid}`
		})
	};

	// 状态颜色
	const getTagType = (item) => {
		if (item.statu == '待审核') {
			return 'warning'
		} else if (item.statu == '已审核') {
			return 'success'
		}
	}

	// 滚动加载
	const scrolltolower = () => {
		loadmore();
	};

	// 请求数据
	const loadmore = async () => {
		status.value = 'loading';
		const owner = pickers.userDict[pickers.userDictCurIndex].value == -1 ? null : pickers
			.userDict[pickers.userDictCurIndex].value
		const params = {
			...limitPage.value, // 直接 params = limitPage.value再去修改params会改变ref的limitPage
			owner: owner,
			cusid: pickers.cusCurId,
			start_date:pickers.dateDict[pickers.dateDictCurIndex].value[0],
			end_date:pickers.dateDict[pickers.dateDictCurIndex].value[1]
		}
		console.log(params)
		
		const res = await app.globalData.http.get(
			`/sale/list${app.globalData.queryParams(params, true, 'comma')}`)
		setTimeout(() => {
			if (res.data.rows.length != 0) {
				list.value.push(...res.data.rows);
				limitPage.value.page++;
			}
			status.value = 'nomore';
		}, 200);
	};


	defineExpose({ setCus, setMainBoxHeight }); // 暴露方法
</script>

<style>
</style>